package miage.rest.resource.misc;

import java.io.IOException;
import org.restlet.data.CharacterSet;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.ext.xml.DomRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author Schwartz Michaël
 */
public class StatsResource extends ServerResource {


	@Get
	@Override
	public Representation get() {

		DomRepresentation result = null;
		try {
			result = new DomRepresentation(MediaType.TEXT_XML);
			result.setCharacterSet(CharacterSet.UTF_8);
			
			Document doc = result.getDocument();

			Element root = doc.createElement("stats");
			
			Element cpu = doc.createElement("cpu");

			Element nbCpu = doc.createElement("count");
			nbCpu.setTextContent(String.valueOf(Runtime.getRuntime().availableProcessors()));

			Element memory = doc.createElement("memory");

			Element freeMemory = doc.createElement("free");
			freeMemory.setTextContent(String.valueOf(Runtime.getRuntime().freeMemory()));

			Element totalMemory = doc.createElement("total");
			totalMemory.setTextContent(String.valueOf(Runtime.getRuntime().totalMemory()));


			cpu.appendChild(nbCpu);

			memory.appendChild(freeMemory);
			memory.appendChild(totalMemory);

			root.appendChild(memory);
			root.appendChild(cpu);

			doc.appendChild(root);
			
			setStatus(Status.SUCCESS_OK);
			
		} catch (IOException exc) {
			setStatus(Status.SERVER_ERROR_INTERNAL);
		}
		
		return result;
	}
}
